package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"net"
	"traning/grpc_authentication/proto"
)

type TestServer struct{
}

func (this *TestServer) GetClass (ctx context.Context, in *proto.RequestData) (*proto.ResponseData, error){
	return &proto.ResponseData{
		Class: "三班",
	}, nil
}

func main() {
	intercptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error){
		mp, _ := metadata.FromIncomingContext(ctx)
		if val, ok := mp["appid"]; ok {
			if val[0] == "970403" {
				fmt.Println("authentic ok !")
			} else {
				fmt.Println("token error!")
				return resp, status.Error(codes.Unauthenticated, "appid 错误！")
			}
		}
		return handler(ctx, req)
	}
	opt := grpc.UnaryInterceptor(intercptor)
	g := grpc.NewServer(opt)
	proto.RegisterTestServerServer(g, &TestServer{})
	lis, _ := net.Listen("tcp", ":8080")
	g.Serve(lis)
}

